using System;
using System.Configuration;
using System.Globalization;
using System.IO;

namespace BSDS.Service.Configuration
{
    public class ConfigurationLoader
    {
        public BsdsServiceConfiguration Load()
        {
            try
            {
                var folderPath = ConfigurationManager.AppSettings["inputFolderPath"];
                var commandTemplate = ConfigurationManager.AppSettings["commandTemplate"];
                var maxFileCopyTime = ConfigurationManager.AppSettings["maxFileCopyTime"];

                var geocodedFilesPergingInDays = int.Parse(ConfigurationManager.AppSettings["geocodedFilesPergingInDays"]);
                var successFilesPergingInDays = int.Parse(ConfigurationManager.AppSettings["successFilesPergingInDays"]);
                var failedFilesPergingInDays = int.Parse(ConfigurationManager.AppSettings["failedFilesPergingInDays"]);
                var cleanTempAfterEachCommand = bool.Parse(ConfigurationManager.AppSettings["cleanTempAfterEachCommand"]);

                var autoExecuteCommand = bool.Parse(ConfigurationManager.AppSettings["autoExecuteCommand"]);
                var autoExecutionTime= DateTime.ParseExact(ConfigurationManager.AppSettings["autoExecutionTime"], 
                    "HH:mm:ss", CultureInfo.InvariantCulture);
                
                var autoExecutionOptions = new AutoExecutionOptions(autoExecuteCommand, autoExecutionTime);

                var filesPruningOptions = new FilesPergingOptions(geocodedFilesPergingInDays, successFilesPergingInDays,
                                                                  failedFilesPergingInDays, cleanTempAfterEachCommand);

                return new BsdsServiceConfiguration(new DirectoryInfo(folderPath), commandTemplate,
                    TimeSpan.Parse(maxFileCopyTime), filesPruningOptions, autoExecutionOptions);
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException("Error loading configuration", ex);
            }
        }
    }
}